import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:isdu_flutter/util/security_util.dart';
import 'package:isdu_flutter/api/server.dart';
import 'dart:convert';
import 'package:isdu_flutter/dialog/loading_dialog.dart';

class UserAPI {

  static final String _doAuth = Server.HOST_MAIN + "/user/signIn";

  static Future verifyIdentity(BuildContext context,
      String stuNum,
      String pwd,
      voidCallback(bool result, int code, String msg)) async {
    var encodedPwd = SecurityUtil.encodeByMD5(pwd);

    // Request server
    Dio dio = new Dio(Server.getDioOptions());
    CancelToken cancelToken = new CancelToken();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => LoadingDialog(
        text: "正在登录",
        onCancel: () {
          cancelToken.cancel("取消登录");
          print("取消登录");
        },
      ),
    );

    Response response = await dio.post(_doAuth,
        data: FormData.from({
          "j_username": stuNum,
          "j_password": encodedPwd
        }), cancelToken: cancelToken)
      .catchError((DioError error) {
        if (CancelToken.isCancel(error)) {
          voidCallback(false, 0, "取消登录");
        } else {
          voidCallback(false, 300, "连接服务器超时");
        }
      });

    var responseStr = response.data.toString();
    if (responseStr == null) {
      voidCallback(false, 404, "Error");
    } else {
      try {
        var jsonObj = jsonDecode(responseStr);
        if (jsonObj["status"] == null || jsonObj["status"] != "failed") {
          voidCallback(true, 0, "登录成功");
        } else {
          voidCallback(false, 0, "学号或教务密码错误");
        }
      } catch(e) {
        voidCallback(false, 404, "Error");
      }
    }
  }

}